package com.googlecode.horncomb.util.lang;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * @author Daniel
 */
public class MapConverter {

	@SuppressWarnings("unchecked")
	public static Map getPropertyMap(Object input,
			final String keyPropertyName, final String valuePropertyName) {
		Map rs = new HashMap();
		if (input == null) {
			return rs;
		}
		Iterator i = null;
		if (input.getClass().isArray()) {
			i = CollectionUtils.arrayToList(input).iterator();
		} else if (input instanceof Iterable) {
			i = ((Iterable) input).iterator();
		} else if (input instanceof Iterator) {
			i = ((Iterator) input);
		}
		if (i == null) {
			throw new IllegalArgumentException(
					"Only be Array, Iterable or Iterator");
		}
		boolean emptyKeyPropName = !StringUtils.hasText(keyPropertyName);
		boolean emptyValPropName = !StringUtils.hasText(valuePropertyName);
		while (i.hasNext()) {
			Object o = i.next();
			Object key = emptyKeyPropName ? o : BeanUtils
					.getNullablePropertyValue(o, keyPropertyName);
			if (key == null) {
				continue;
			}
			Object value = emptyValPropName ? o : BeanUtils
					.getNullablePropertyValue(o, valuePropertyName);
			rs.put(key, value);
		}
		return rs;
	}

}
